import React, { useState, useEffect ,createContext, useContext } from 'react';
import styles from './index.module.scss';

import { Button, Table, Pagination, Dialog, Form } from '@alifd/next';

import { useLocation, useParams } from 'ice';

// 获取api
import { getDeviceInfo } from '../../services/deviceInfo.js';

import CustomIcon from '@/components/CustomIcon';

import DhcpForm from './DhcpForm';

const PAGE_SIZE = 10;

export const FormContext = createContext({});

const DhcpTab = (props) => {
    const ID = useParams().id;

    let [ form, onForm ] = useState({}),
        [ showDialog, onShowDialog] = useState(false),
        [ isAdd, onAdd ] = useState(false),
        [id,onId] = useState(-1),
        [currentPage, onCurrentPage] = useState(1),
        [dataSource, onDataSource] = useState([]);

    let interSel = [],
        dnsSel = [],
        onDevice = props.onDevice;

        useEffect(()=>{
          getDeviceInfo(ID).then(result => {
              console.log('result', result);
              if(result.code == 200) {
                  onDataSource(result.msg[0].dhcp)
              }
          })
      },[]);


    // interface下拉选选项
    props.rowData[0].interfaces.forEach(item => {
      interSel.push({
        value: item.pciaddr,
        label: item.name + '(' + item.IPv4 + '/' + item.IPv4Mask + ')'
      })
    });

    // dns下拉选选项
    dnsSel.push(
      {
        label: '8.8.8.8',
        value: '8.8.8.8'
      },
      {
        label: '8.8.4.4',
        value: '8.8.4.4'
      },
    )        
    // 分页
    let d = dataSource.slice((currentPage-1)*PAGE_SIZE,currentPage*PAGE_SIZE);
    const onPageChange = currentPage => {
        onCurrentPage(currentPage)
    };

    const handleDialog = (e, record, index) => {
      onShowDialog(true)
      if(record) {
        // 修改
        console.log(record)
        onForm(record)
        onAdd(false)
        onId(index)
      } else {
        onForm({})
        onAdd(true)
        onId(-1)
      }
    }

    const onOk = (e, flag)=>{
      if(flag) {
        // 新增
        console.log('新增确认', form)
        dataSource.push(form);
      } else {
        // 编辑
        console.log('编辑确认', form)
        dataSource[id] = form;
        onDataSource([...dataSource])
      }
      onDevice(a=>{
        return {
          ...a,
          dhcp: dataSource
        }
      })
      onShowDialog(false)
    };

    const handleDelete = (e, id) => {
      const dialog = Dialog.confirm({
        title: 'Delete DHCP',
        content: 'Are you sure to delete DHCP?',
        messageProps:{
          type: 'warning'
        },
        footer: (
          <>
            <Button warning type="primary" onClick={
              () => {
                dataSource.splice(id,1);
                onDataSource([...dataSource]);
                onDevice(a=>{
                  return {
                    ...a,
                    dhcp: dataSource
                  }
                });
                dialog.hide()
              }
            }>
                Delete
            </Button>
            <Button style={{marginLeft: '10px'}} onClick={() => dialog.hide()}>
                Cancel
            </Button>
          </>
        )
      });
    }
    

    // table的列配置
    const tableConfig = [
      {
        title: 'Interface',
        dataIndex: 'interface',
        sortable: true
      },
      {
        title: 'IP Range',
        dataIndex: 'range', // 合并处理
        sortable: true,
        content: (value, index, record) => {
          return (
            <span>{`${record.rangeStart}-${record.rangeEnd}`}</span>
          )
        }
      },
      {
        title: 'DNS',
        dataIndex: 'dns',
        sortable: true,
        content: (value, index, record) => {
          return value + '';
        }
      },
      {
        title: 'MAC Assigned',
        dataIndex: 'macAssign',
        sortable: true,
        content: (value, index, record) => {
          return (
            // <span>{value.length == 0 ? 'No' : 'Yes'}</span>
            <span>no</span>
          )
        }
      },
      {
        title: 'Actions',
        dataIndex: 'actions',
        sortable: false,
        content: (value, index, record) => {
          return (
            <>
              <Button className={`round-button ${styles['dhcp-set']}`} onClick={(e) => handleDialog(e,record, index)} type="primary">
                  <CustomIcon type="iconsetting"/>
              </Button>
              <Button className="round-button" type="primary" warning onClick={(e) => handleDelete(e,index)}>
                  <CustomIcon type="icondelete"/>
              </Button>
            </>
          )
        }
      }
    ];

    return (
      <>
        <div className={styles['dhcp-button']}>
            <Button type="secondary" onClick={handleDialog}>Add DHCP</Button>
        </div>
        <div className={styles['dhcp-table']}>
            <Table
                type="primary"
                dataSource={d}
            >
            {
                tableConfig.map((item,i) => {
                return (
                    <Table.Column 
                      key={`table${i}`} 
                      title={item.title} 
                      dataIndex={item.dataIndex} 
                      sortable={item.sortable}
                      cell={item.content} 
                    />
                )
                })
            }
            </Table>
        </div>
        <div className={styles['dhcp-pagination']}>
            <Pagination 
              onChange={onPageChange}
              total={dataSource.length}
              pageSize={PAGE_SIZE}
              pageShowCount={5} 
            />
        </div>
        <Dialog
          visible={showDialog}
          onOk={
            (e) => {
              if(isAdd) {
                // 新增
                return onOk(e,true)
              } else {
                return onOk(e,false)
              }
            }
          }
          onCancel={()=>onShowDialog(false)}
          onClose={()=>onShowDialog(false)}
        >
          <FormContext.Provider value={form}>
            <DhcpForm 
              key="displayForm" 
              formData={form} 
              interSel={interSel} 
              dnsSel={dnsSel} 
              onForm={onForm} 
            />
          </FormContext.Provider>
        </Dialog>
      </>
    )
};

export default DhcpTab;